package cn.dl.com;

import com.sun.org.apache.bcel.internal.generic.DCONST;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.net.URL;
import java.nio.file.Paths;

/**
 * @Author: dlc
 * @Date: 2022/1/11 - 17:00
 */
public class CreateIndex {

    public static void main(String[] args) throws Exception{
        // 构建分词器（标准的，自带的）
//        StandardAnalyzer standardAnalyzer = new StandardAnalyzer();

        // ik分词器
        IKAnalyzer ikAnalyzer = new IKAnalyzer();

        // 构建 IndexWriterConfig
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(ikAnalyzer);
        // 构建文档写入器(索引构建之后的地址)
        String url = "C:\\mycode\\me\\gitee\\elasticstack\\demo01_lucene\\src\\main\\resources\\index";
        IndexWriter indexWriter = new IndexWriter(FSDirectory.open(Paths.get(url)), indexWriterConfig);
        // 读取文件
        String fileUrl = "C:\\mycode\\me\\gitee\\elasticstack\\demo01_lucene\\src\\main\\resources\\data";
        File files= new File(fileUrl);
        File[] filesArr = files.listFiles();

        for(File file : filesArr) {
            // 创建文档
            Document document = new Document();
            // 创建Filed,进行分词，并且存储
            document.add(new TextField("file_name", file.getName(), Field.Store.YES));
            // 进行分词，但是不存储
            document.add(new TextField("content", FileUtils.readFileToString(file,"gbk"), Field.Store.NO));
            // 保存目录，部分词，存储
            document.add(new StoredField("path", file.getAbsolutePath()));

            // 将文档写入索引
            indexWriter.addDocument(document);
        }
        // 关闭
        indexWriter.close();
    }
}
